import Axios, { AxiosResponse } from 'axios'
import qs from 'qs'
import { parseJson } from '@/utils'
import { Message } from '@arco-design/web-vue'
import useUserStore from '@/store/modules/user'
import router from '@/router'

export const baseURL = import.meta.env.VITE_BASE_URL
// export const baseURL = 'https://api.saas.selleroa.com/'

export const CONTENT_TYPE = 'Content-Type'

export const FORM_URLENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'

export const APPLICATION_JSON = 'application/json; charset=UTF-8'

export const TEXT_PLAIN = 'text/plain; charset=UTF-8'

export const ACCEPT = '*/*'

export const DEFAULT_TIME = 30000

const httpRequestList = []

const service = Axios.create({
  baseURL,
  timeout: DEFAULT_TIME,
})
service.interceptors.request.use(
  (config: any) => {
    // 传token
    const userStore = useUserStore()
    config.headers['session-token'] = userStore.token
    config.headers['session-menu-url'] = router.currentRoute.value.fullPath
    // 返回格式
    config.headers['accept'] = ACCEPT
    // 测试暂时传递两个参数---start
    config.headers['session-company-id'] = userStore.companyId
    config.headers['session-user-id'] = userStore.userId
    config.headers['session-user-name'] = encodeURIComponent(userStore.userName)
    // config.headers['session-company-id'] = 'test01'
    // config.headers['session-user-id'] = 'zxy'

    // 测试暂时传递两个参数---end

    // 是否需要中断请求
    if (config.isCancel) {
      config.cancelToken = new Axios.CancelToken((c) => {
        httpRequestList.push(c)
      })
    }
    // 判断content-type
    if (!config.headers[CONTENT_TYPE]) {
      config.headers[CONTENT_TYPE] = APPLICATION_JSON
    }
    if (config.headers[CONTENT_TYPE] === FORM_URLENCODED) {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (error) => {
    return Promise.reject(error.response)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => {
    if (response?.config?.responseType == 'blob') {
      return response
    }
    if (response.status === 200 && response.config?.backAllResult) {
      return response
    }
    response.data = parseJson(response.data, response.data)
    if (response.status === 200 && response.data.code?.toUpperCase() == 'SUCCESS') {
      return response.data
    } else {
      Message.warning(`【${response.data.code}】${response.data.errorMsg}`)
      throw new Error(response.status.toString())
    }
  },
  (error) => {
    console.log(error)
    Message.clear()
    if (error.message.includes('timeout')) {
      Message.warning('请求超时，请重新操作!')
    }
    const responseCode = error.response.status
    switch (responseCode) {
      case 401: {
        const userStore = useUserStore()
        userStore.logout()
        router.replace({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } })
        break
      }
      case 403:
        Message.error('功能未授权')
        break
      case 429:
        Message.error('操作太频繁，请稍后再试')
        break
      case 503:
        Message.error('服务器开小差咯！')
        break
      case 500:
        if (error.response.data.code == 'SYS_ERROR' || error.response.data.code == 'Internal Server Error') {
          Message.error('服务器开小差咯!')
        } else {
          Message.error({
            content: error.response.data.errorMsg,
            duration: 4000,
          })
        }
        break
      default:
        Message.error({
          content: error.response.data.errorMsg,
          duration: 4000,
        })
    }
    return Promise.reject(error.response)
  }
)

export default service
